<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Equipment Config</title>
	<link rel="stylesheet" href="../js/easyui/themes/bootstrap/easyui.css">
	<link rel="stylesheet" href="../js/easyui/themes/icon.css">
	<link rel="stylesheet" href="../js/easyui/themes/color.css">
	<link rel="stylesheet" href="../css/index-ui.css" />
	<script type="text/javascript" src="../js/easyui/jquery.min.js"></script>
	<script type="text/javascript" src="../js/easyui/jquery.easyui.min.js"></script>
	<!--script type="text/javascript" src="../js/echarts.min.js"></script-->
	<script type="text/javascript" src="../js/kchart.js"></script>
	<script type="text/javascript" src="../js/ams.util.js"></script>
	<script type="text/javascript" src="../js/webapi.js"></script>
</head>

<body onload="page_init()">
	<div id="lotlog_filter" style="padding:5px;padding-left:1px;padding-right:10px">
		<div style="float:left;padding-left:10px">
			<a href="#" class="easyui-menubutton" style="width:115px" data-options="plain:false, menu:'#mdetail',iconCls:'icon-help'">Details...</a>
		</div>
		<div id="mdetail" style="width:50px">
			<div onclick="on_view_lot_data()"> Process Data </div>
			<div onclick="on_view_log()">Process Log</div>
			<div onclick="on_wafer_run_history()">Wafer Run History</div>
			<!--<div disabled=true onclick="on_view_stat_chart()">Wafer Bar Chart</div>-->
			<div style="display:none" onclick="on_view_stat_chart()">Wafer Bar Chart</div>
		</div>
		<div style="float:right;padding-left:10px">
			<a class="easyui-linkbutton" style="width:100px" iconCls="icon-search" onclick="on_query_lotinfo()">Query</a>
		</div>
		<div style="float:right;padding-right:10px">
			<div style="float:left;padding-top:6px;padding-right:10px"><label> Date Filter: </label></div>
			<input id="filter_start_date" class="easyui-datebox" style="width:115px">
			<label> --- </label>
			<input id="filter_end_date" class="easyui-datebox" style="width:115px">
		</div>
		<div style="float:right;padding-right:10px">
			<div style="float:left;padding-top:6px;padding-right:10px"><label> Lot ID: </label></div>
			<input id="filter_lot_id" type="text" value="" style="width: 120px; height: 27px; border: 1px solid #dddddd;border-radius: 4px;">
			<label> Recipe Name: </label>
			<input id="filter_rcp_name" type="text" value="" style="width: 120px; height: 27px; border: 1px solid #dddddd;border-radius: 4px;">
		</div>
	</div>
	<br/><br/>
	<div style="height:94%">
		<table id="eq_lotlog_grid" class="easyui-datagrid" title="" style="width:100%;height:100%" pagination="false"
				data-options="singleSelect:'true',loadMsg:'Loading Data ......'">
			<thead>
				<tr>
					<th data-options="field:'id'" hidden="true">id</th>
					<th data-options="field:'st',width:120">Start Time</th>
					<th data-options="field:'et',width:120">End Time</th>
					<th data-options="field:'ln',width:125">Lot Name</th>
					<th data-options="field:'jn',width:125">Job Name</th>
					<th data-options="field:'lid',width:125">Lot ID</th>
					<th data-options="field:'rcp',width:125">Recipe Name</th>
					<th data-options="field:'fid',width:125">Foup ID</th>
					<th data-options="field:'cid',width:70">Carrier ID</th>
					<th data-options="field:'path',width:70">Path</th>
					<th data-options="field:'slot',width:40">Slot</th>
					<th data-options="field:'res',width:50">Result</th>
					<th data-options="field:'sn',width:60">Success</th>
					<th data-options="field:'op',width:100">Operator</th>
					<th data-options="field:'wph',width:70">WPH</th>
					<th data-options="field:'info'" hidden="true">info</th>
					<th data-options="field:'lmax'" hidden="true">max</th>
				</tr>
			</thead>
		</table>
	</div>

	<!-- statistic chart window -->
	<div id="window_stat_chart" class="easyui-window" title="Statistic Chart"
	data-options="modal:true,closed:true,iconCls:'icon-help',cls:'c1'" style="width:850px;height:600px;padding:10px;">
		<div id='div_header' style="position:fixed;opacity:0.8;background:#ffffff;"> <!--  style="position:fixed" -->
		<table style="color:#666666;border:solid thin #ffffff">
			<tr>
				<td>Carrier ID: </td>
				<td> carrier-8192 </td>
			</tr>
			<tr>
				<td width="100">Start Time:</td>
				<td width="180">2018/04/24 16:26:22</td>
				<td width="100">End Time: </td>
				<td width="180">2018/04/24 16:56:22</td>
			</tr>
			<tr>
				<td width="100">Wafer Count:</td>
				<td width="180"> 25 </td>
				<td width="100">Success Count: </td>
				<td width="180"> 25 </td>
			</tr>
		</table>
		<div id="tb4" style="position:fixed;opacity:0.8;background:#ffffff;">
			<td width="145px"> Current Loop: </td>
			<select class="easyui-combobox" id="loop-num-chart" name="state" style="width:60px;" editable="false" data-options="panelHeight:'auto',panelMaxHeight:200"></select>
		</div>
		</div>
		<canvas id="canvas_stat_chart" left="50" width="4000" height="3000" background-color="#333333" style="border:0px solid #c3c3c3;">
				Your browser does not support the canvas element.
		</canvas>
	</div>

	<div id="window_detail_log" class="easyui-window" title="Lot Detail Log"
		data-options="modal:true,closed:true,iconCls:'icon-help',cls:'c1'" style="width:850px;height:500px;padding:10px;">
		<div class="easyui-layout" style="width:100%;height:100%;">
			<div data-options="region:'center',title:'',iconCls:'icon-help'">
				<table id="tbl_lotlog_detail" class="easyui-datagrid" style="width:99%;height:95%"
						iconCls="icon-help" rownumbers="true" pagination="false"
						data-options="singleSelect:'true',loadMsg:'Loading Data ......',toolbar:'#tb3'">
					<thead>
						<tr>
							<th data-options="field:'time',width:160">Time</th>
							<th data-options="field:'cnt',width:560">Content</th>
						</tr>
					</thead>
				</table>
				<div id="tb3" style="float:right;padding:2px 5px;">
					<td width="145px"> Current Loop: </td>
						<select class="easyui-combobox" id="loop-num-detail" name="state" style="width:60px;" editable="false" data-options="panelHeight:'auto',panelMaxHeight:200"></select>
				</div>
			</div>
		</div>
	</div>

	<div id="window_wafer_run_history" class="easyui-window" title="Wafer Run History"
		data-options="modal:true,closed:true,iconCls:'icon-help',cls:'c1'" style="width:1000px;height:600px;padding:10px;">
		<div class="easyui-layout" style="width:100%;height:100%;">
			<div data-options="region:'center',title:'',iconCls:'icon-help'">
				<table id="tbl_lotlog_wrh" class="easyui-datagrid" style="width:99%;height:95%"
						iconCls="icon-help" pagination="false"
						data-options="singleSelect:'true',loadMsg:'Loading Data ......',toolbar:'#tb5'">
					<thead>
						<tr>
							<th data-options="field:'Wafer',width:80">Wafer</th>
							<th data-options="field:'Index',width:40">Index</th>
							<th data-options="field:'Module',width:90">Module</th>
							<th data-options="field:'PrTime',width:125">PrTime</th>
							<th data-options="field:'PoTime',width:125">PoTime</th>
							<th data-options="field:'EITime',width:60">EITime</th>
							<th data-options="field:'ProcessRecipe',width:120">ProcessRecipe</th>
							<th data-options="field:'ProcessData',width:450">ProcessData</th>
							<th data-options="field:'Color',hidden:true">Color</th>
						</tr>
					</thead>
				</table>
				<div id="tb5" style="float:right;padding:2px 5px;">
					<td width="145px"> Current Loop: </td>
						<select class="easyui-combobox" id="loop-num-wrh" name="state" style="width:60px;" editable="false" data-options="panelHeight:'auto',panelMaxHeight:200"></select>
				</div>	
			</div>
		</div>
	</div>
	
	<div id="window_lot_data" class="easyui-window" title="Lot Data"
			data-options="modal:true,closed:true,iconCls:'icon-help',cls:'c1'" style="width:850px;height:600px;padding:10px;">
			<div id="tabs" class="easyui-tabs" style="width:100%;height:100%">
				<div title="By Wafer" style="padding:10px">
					<div class="easyui-layout" style="width:100%;height:100%;">
						<div data-options="region:'west',split:true" title="Wafers" style="width:150px;">
							<ul id="tree_wafer" title="" class="easyui-tree" style="height:100%"></ul>
						</div>
						<div data-options="region:'center',title:'',iconCls:'icon-help'">
							<table id="tbl_by_wafer" class="easyui-datagrid" title="" style="width:100%;height:100%" pagination="false"
								data-options="singleSelect:'true',loadMsg:'Loading Data ......',toolbar:'#tb'">
							</table>
							<div id="tb" style="float:right;padding:2px 5px;">
								<td width="145px"> Current Loop: </td>
									<select class="easyui-combobox" id="loop-num-wafer" name="state" style="width:60px;" editable="false" data-options="panelHeight:'auto',panelMaxHeight:200">
								</select>
								<a href="#" class="easyui-linkbutton" iconCls="icon-search" style="width:100px" onclick="on_by_wafer_chart()">Chart</a>
							</div>
						</div>
					</div>
				</div>
				<div title="By Chamber" style="padding:10px">
					<div class="easyui-layout" style="width:100%;height:100%;">
						<div data-options="region:'west',split:true" title="Modules" style="width:150px;">
							<ul id="tree_chamber" title="" class="easyui-tree" style="height:100%"></ul>
						</div>
						<div data-options="region:'center',title:'',iconCls:'icon-help'">
							<table id="tbl_by_chamber" class="easyui-datagrid" title="" style="width:100%;height:100%" pagination="false"
								data-options="singleSelect:'true',loadMsg:'Loading Data ......',toolbar:'#tb2'">
							</table>
							<div id="tb2" style="float:right;padding:2px 5px;">
								<td width="145px"> Current Loop: </td>
									<select class="easyui-combobox" id="loop-num-chamber" name="state" style="width:60px;" editable="false" data-options="panelHeight:'auto',panelMaxHeight:200">
								</select>
							</div>
						</div>
					</div>
				</div>
				<div title="Multi Plotting" style="padding:10px">
					<div class="easyui-layout" style="width:100%;height:100%;">
						<div class="easyui-layout" data-options="region:'west',split:true" title="Wafers" style="width:200px">
							<div data-options="region:'north',split:true" style="height: 250px;">
								<ul id="tree_wafer_mp" title="" class="easyui-tree" style="height:100%"></ul>
							</div>
							<div data-options="region:'center',fit:true">
								<a class="easyui-linkbutton" style="width:80px" iconCls="icon-add" onclick="on_mp_add()">Add</a>
								<!-- a class="easyui-linkbutton" style="width:80px" iconCls="icon-delete" onclick="on_mp_delete()">Delete</a -->
								<a class="easyui-linkbutton" style="width:80px" iconCls="icon-cancel" onclick="on_mp_reset()">Reset</a>
								<input class="easyui-combobox" id="combo_var_mp" style="width:98%;" editable="false"
									data-options="panelHeight:'auto',panelMaxHeight:200,valueField:'id',textField:'text'">
								</input>
								<table id="tbl_wfr_pm_mp" class="easyui-datagrid" title="" style="width:100%;height:200px" pagination="false"
									data-options="singleSelect:false,checkOnSelect:false">
									<thead>
										<tr>
											<th data-options="field:'wafer',width:70">Wafer</th>
											<th data-options="field:'pm',width:70">PM</th>
											<th data-options="field:'visible',checkbox:true,styler:mp_dg_styler"></th>
										</tr>
									</thead>
								</table>
							</div>
						</div>
						<div data-options="region:'center',title:'',iconCls:'icon-help'">
							<div id="chart_container_mp" style="height:100%; width:100%;border: 0px solid #ff0000"></div>
						</div>
					</div>
				</div>
			</div>
	</div>
	<div id="wnd_by_wafer_data_chart" class="easyui-window" title="Lot Data Chart"
		data-options="modal:true,closed:true,iconCls:'icon-help',cls:'c7'" style="width:800px;height:540px;padding:10px;">
		<div id="chart_container" style="height:100%; width:100%;border: 0px solid #ff0000"></div>
	</div>
</body>

<script language="javascript"> 

var g_by_wafer_proc_data = {}
var g_dyn_chart = null
var eqn = null
var row = null

$.fn.datebox.defaults.formatter = function(date){
	var y = date.getFullYear();
	var m = date.getMonth()+1;
	var d = date.getDate();
	return y+'-'+m+'-'+d;
};
$.fn.datebox.defaults.parser = function(s){
	var t = Date.parse(s);
	if (!isNaN(t)){
		return new Date(t);
	} else {
		return new Date();
	}
}	

function __fmt_time(value, row, index) {
	if (index < 3) return value
	var time = new Date(value)
	return datetime_format(time, 'yyyy-MM-dd hh:mm:ss.SSS')
}

function __fmt_val(value, row, index) {
	var num = new Number(parseFloat(value))
	return  num.toFixed(4)
}

// result data is stored in g_by_wafer_proc_data
function get_wafer_pm_data(lot_id, wafer_id, unit_name, info)
{
	var __data = null
	$.ajaxSettings.async = false
	if (ams_is_sim_mode()) {
		$.getJSON('lotlog_data_by_wafer_01.json', function(json_data) {
			json_data.columns[0][1]['formatter'] = __fmt_time
			for (var k = 2; k < json_data.columns[0].length; k++) {
				json_data.columns[0][k]['formatter'] = __fmt_val
			}
			var time_start = new Date().getTime() - 3600*1000
			var rnd_val = []
			for (var k = 0; k < 5; k++) {
				rnd_val[k] = 1000-(Math.random()*2000)//2000*Math.random()
			}
			for (var i = 0; i < 300; i++) {
				var record = {}
				record['no'] = i+1
				record['time'] = time_start + 50*i
				for (var k = 0; k < 5; k++) {
					rnd_val[k] = rnd_val[k] + Math.random() * 21 - 10
					var dn = 'data0' + (k+1)
					record[dn] = rnd_val[k]
				}
				json_data.rows.push(record)
			}
			__data = json_data
		})
	} else {
		// TODO: call 'getProcDataByWafer'
		// g_by_wafer_proc_data = ...
		var loopNum = $('#loop-num-wafer').combobox('getValue');
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("getProcDataByWafer"),
			data:JSON.stringify({
				"eqName":eqn,
				"lotId":lot_id,
				"waferId":wafer_id,
				"unitId":unit_name,
				"info":info,
				"loopNum":loopNum
			}),
			dataType: 'json',
			success: function (json_data) {
			//	console.log(json_data)
				if (json_data.d == "") {
					__data = null
				}
				else {
					__data = JSON.parse(json_data.d)
				}
			},
			error: function (response) {
				//alert(errorThrown.message);
				//alert('Error: ' + response.responseText)
				$.messager.alert("Error", "Error: " + response.responseText, "error")
				__data = null
			}
		})
	}
	return __data
}

function __fill_by_wafer_grid(lot_id, wafer_id, unit_name, info)
{
	g_by_wafer_proc_data = get_wafer_pm_data(lot_id, wafer_id, unit_name, info)
	g_by_wafer_proc_data.columns[0][1]['formatter'] = __fmt_time
	if (g_by_wafer_proc_data == null) {
		var item = $('#tbl_by_wafer').datagrid('getRows')
		if (item) {
			for (var i = item.length - 1; i >= 0; i--) {
				var index = $('#tbl_by_wafer').datagrid('getRowIndex', item[i]);
				$('#tbl_by_wafer').datagrid('deleteRow', index);
			}
		}
		$.messager.alert("Tips", "Data error.", "info");
	}
	 else {
		$('#tbl_by_wafer').datagrid({
			columns:g_by_wafer_proc_data.columns,
			data:g_by_wafer_proc_data.rows,
			onLoadSuccess: function() {
				$(this).datagrid('freezeRow',0).datagrid('freezeRow',1).datagrid('freezeRow', 2)
			},
			rowStyler: function(index, row) {
				if (index < 3) {
					return 'background-color:#fff2cc;color:#000000;font-weight:bold;'
				}
			}
		})
	}
}

function __fill_by_chamber_grid(lotId, unitName,info)
{
	if (ams_is_sim_mode()) {
		$.getJSON('lotlog_data_by_chamber_01.json', function(json_data) {
			$('#tbl_by_chamber').datagrid({
				columns:json_data.columns,
				data:json_data.rows,
				rowStyler: function(index, row) {
					if ((row.no == undefined || row.no == '' || row.no == 'Total') &&
						(row.wafer != undefined)) {
                        return 'background-color:#fff2cc;color:#000000;font-weight:bold;'
                    }
                }
			})
		})
	} else {
		// TODO: call 'getProcDataByUnit'
		var loopNum = $('#loop-num-chamber').combobox('getValue');
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("getProcDataByUnit"),
			data:JSON.stringify({
				"eqName":eqn,
				"lotId":lotId,
				"unitName":unitName,
				"info":info,
				"loopNum":loopNum
			}),
			dataType: 'json',
			success: function (json_data) {
				console.log(JSON.parse(json_data.d))
				$('#tbl_by_chamber').datagrid({
					columns:JSON.parse(json_data.d).columns,
					data:JSON.parse(json_data.d).rows,
					rowStyler: function(index, row) {
						if ((row.no == undefined || row.no == '' || row.no == 'Total') &&
							(row.wafer != undefined)) {
	                        return 'background-color:#fff2cc;color:#000000;font-weight:bold;'
	                    }
	                }
				})
			},
			error: function (response) {
				//alert(errorThrown.message);
				//alert('Error: ' + response.responseText)
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});
	}
}

function isRealNum(val){
    // 先判定是否为number
    if(typeof val !== 'number'){
      return false;
    }
    if(!isNaN(val)){
        return true;
    }else{
        return false;
    }
}

var g_rtchart = undefined
function __load_by_wafer_chart()
{
	if (g_rtchart == undefined) {
		g_rtchart = new RTChart('chart_container', false)
	}
	g_rtchart.reset()

	var rows = $('#tbl_by_wafer').datagrid('getRows')
	var col_count = $('#tbl_by_wafer').datagrid('getColumnFields').length - 2
	var colname_array = []
	var filter = false;
	for (var i = 0; i < col_count; i++) {
		var col = $('#tbl_by_wafer').datagrid('getColumnOption', 'data0' + (i+1))
		var field = col['field'];
		if (isRealNum(rows[3][field])){
			colname_array[i] = col['title']
			filter = true;
		}
	}
//	console.log(colname_array)
	if (filter){
		// 含有非数字列，需要过滤掉。
		var newRows = new Array();
		for (var i = 0; i < rows.length; i++) { 
			newRows[i] = new Array();
			newRows[i]['no'] = rows[i]['no'];
			newRows[i]['time'] = rows[i]['time'];
			for (var j = 0; j < col_count; j++) {
			var col = $('#tbl_by_wafer').datagrid('getColumnOption', 'data0' + (j+1))
			var field = col['field'];
			if (isRealNum(rows[i][field])){
				newRows[i][field] = rows[i][field];
			}
		 }
		}
		g_rtchart.add_serie(newRows, colname_array)
	}else{
		g_rtchart.add_serie(rows, colname_array)
	}

	return
}

function on_by_wafer_chart()
{
	if ($('#tbl_by_wafer').datagrid('getRows').length <= 3) {
		$.messager.alert('AMS System', 'No data. ')
		return
	}

	$('#wnd_by_wafer_data_chart').window({maximized: true}).window('open')

	__load_by_wafer_chart()
}

function page_init()
{
	// init default filter
	var tmpday = new Date()
	var end_day = tmpday.getMonth() + 1 + '/' + tmpday.getDate() + '/' + tmpday.getFullYear()
	tmpday.setDate(tmpday.getDate() - 7)
	// var start_day = tmpday.getMonth() + 1 + '/' + tmpday.getDate() + '/' + tmpday.getFullYear()
	var start_day = tmpday.getMonth() + 1 + '/' + tmpday.getDate() + '/' + tmpday.getFullYear()
	eqn = get_page_param('eq')
	
	$('#filter_start_date').datebox('setValue', start_day)
	$('#filter_end_date').datebox('setValue', end_day)

	$('#tree_wafer').tree({
			onClick: function(node) {
				var unitName = node.text
				var waferNode = $('#tree_wafer').tree('getParent', node.target)
				if (waferNode != undefined) {
					var waferId = waferNode.text
					var lotId = $('#eq_lotlog_grid').datagrid('getSelected').id
					var info = null
					for (var i = 0; i < waferNode.children.length; i++) {
						if (unitName == waferNode.children[i].text) {
							info = waferNode.children[i].info
							break
						}
					}
				//	console.log(lotId + ': ' + waferId + '/' + unitName)
				//	console.log(info)
					__fill_by_wafer_grid(lotId, waferId, unitName, info)
				}
			}
		})

	$('#tree_chamber').tree({
			onClick: function(node){
				var unitName = node.text
				var lotId = $('#eq_lotlog_grid').datagrid('getSelected').id
				var info = $('#eq_lotlog_grid').datagrid('getSelected').info
				__fill_by_chamber_grid(lotId, unitName,info)
				}
			})

	// init hidden sub-windows
	// [stat chart window]
	$('#window_stat_chart').window({
		onOpen:function(){
			var loopMax = $('#eq_lotlog_grid').datagrid('getSelected').lmax;
			var data;
			data = [];
			for (var i = 1; i <= loopMax; i++)
			{
				data.push({ "text": i, "value": i });
			}
			$("#loop-num-chart").combobox("loadData", data);
			$('#loop-num-chart').combobox('select',data[0].text);

			on_refresh_chart();
		}
	})

	on_query_lotinfo()
}

function on_refresh_chart()
{
	if (ams_is_sim_mode()) {
	$.getJSON("lotlog_stat_chart_01.json", function(json_data){
		//	console.log(json_data)
			draw_stat_chart(json_data)
		})
	} else {
		// var row = $('#eq_lotlog_grid').datagrid('getSelected')
		// var __id = row.id
		// $.post(getWebServiceUrl("getGraphicsData"),
		// 		{ 'id':__id },
		// 		function(json_data) {
		// 			draw_stat_chart(json_data)
		// 		})
		// .fail(function(response) {
		// 	alert('Error: ' + response.responseText);
		// })
		var loopNum = $('#loop-num-chart').combobox('getValue');
		row = $('#eq_lotlog_grid').datagrid('getSelected')
		var __id = row.id
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("getGraphicsData"),
			data:JSON.stringify({
				"eqName":eqn,
				"lotId":__id,
				"info":row.info,
				"loopNum":loopNum
			}),
			dataType: 'json',
			success: function (json_data) {
				console.log(JSON.parse(json_data.d))
				draw_stat_chart(JSON.parse(json_data.d))
			},
			error: function (response) {
				//alert(errorThrown.message);
				//alert('Error: ' + response.responseText)
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});
	}
}

function on_query_lotinfo()
{
	// var eqn = get_page_param('eq')
	var flt_lot_id = document.getElementById('filter_lot_id').value
	var flt_rcp_name = document.getElementById('filter_rcp_name').value
	var start_t = $('#filter_start_date').datebox('getValue')
//	var ss = $("#filter_start_date").val()
	var end_t = $('#filter_end_date').datebox('getValue')
	//var __param = { 'eqName':eqn, 'cid':flt_cid, 'startTime':start_t,  'endTime':end_t  }
	//console.log(__param)
	if (ams_is_sim_mode()) {
		$.getJSON('lotlog_lot_list_01.json',
		function(json_data){
			$('#eq_lotlog_grid').datagrid({
				data:json_data.rows
			})
		})
	} else {
		// $.post(getWebServiceUrl("getLotLog"),
		// 	__param,
		// 	function(json_data) {
		// 		$('#tbl_lotlog_detail').datagrid({
		// 			data: json_data.rows
		// 		})
		// 	}, 'json')
		// 	.fail(function(response) {
		// 		alert('Error: ' + response.responseText);
		// 	})
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("getLotLog"),
			data:JSON.stringify({
				"eqName":eqn,
				"lotId":flt_lot_id,
				"rcpName":flt_rcp_name,
				"sTime":start_t,
				"eTime":end_t
			}),
			dataType: 'json',
			success: function (json_data) {
				console.log(JSON.parse(json_data.d))
				$('#eq_lotlog_grid').datagrid({
					data:JSON.parse(json_data.d).rows
				})
			},
			error: function (response) {
				//alert(errorThrown.message);
				//alert('Error: ' + response.responseText)
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});
	}
}

/*
function on_view_data_by_wafer()
{
	alert('By Wafer!')
}

function on_view_data_by_chamber()
{
	alert('By chamber!')
}
*/

function __fill_wafer_tree(json_data, tree_name)
{
	var tree_data = []
	for (var i = 0; i < json_data.length; i++) {
		var rootNode = {}
		rootNode['text'] = json_data[i]['wafer']
		rootNode['state'] = 'closed'
		if (json_data[i]['chambers'].length > 0) {
			var childrenNode = []
			var info = []
			for (var k = 0; k < json_data[i]['chambers'].length; k++) {
				childrenNode.push( { 'text':json_data[i]['chambers'][k]['name'],'info':json_data[i]['chambers'][k]['info'] } )
				// info.push( { 'text':json_data[i]['chambers'][k]['info'] } )
			}
			rootNode['children'] = childrenNode
			// rootNode['attributes'] = info
		}
		tree_data.push(rootNode)
	}
	$(tree_name).tree({
			data: tree_data,
	})
}

function __fill_chamber_tree(json_data)
{
	$('#tree_chamber').tree({
		data: json_data
	})
}

function init_wafer_tree()
{
	if (ams_is_sim_mode()) {
		$.getJSON('lotlog_get_wafer_01.json', function(json_data) {
			__fill_wafer_tree(json_data, '#tree_wafer')
			__fill_wafer_tree(json_data, '#tree_wafer_mp')
		})
	} else {
		// $.post(getWebServiceUrl('getLotWaferUnit'),
		// 	{}, // TODO:
		// 	function(json_data) {
		// 		__fill_wafer_tree(json_data)
		// 	}
		// 
		var loopNum = $('#loop-num-wafer').combobox('getValue');
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("getLotWaferUnit"),
			data:JSON.stringify({
				"eqName":eqn,
				"lotId":row.id,
				"loopNum":loopNum
			}),
			dataType: 'json',
			success: function (json_data) {
				console.log(JSON.parse(json_data.d))
				__fill_wafer_tree(JSON.parse(json_data.d), '#tree_wafer')
				__fill_wafer_tree(JSON.parse(json_data.d), '#tree_wafer_mp')
			},
			error: function (response) {
				//alert(errorThrown.message);
				//alert('Error: ' + response.responseText)
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});
	}
}

function init_chamber_tree()
{
	if (ams_is_sim_mode()) {
		$.getJSON('lotlog_get_chamber_01.json', function(json_data) {
			__fill_chamber_tree(json_data)
		})
	} else {
		// $.post(getWebServiceUrl('getLotUnitList'),
		// 	{}, // TODO:
		// 	function(json_data) {
		// 		__fill_chamber_tree(json_data)
		// 	}
		// )
		var loopNum = $('#loop-num-chamber').combobox('getValue');
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("getLotUnitList"),
			data:JSON.stringify({
				"eqName":eqn,
				"lotId":row.id,
				"info":row.info,
				"loopNum":loopNum
			}),
			dataType: 'json',
			success: function (json_data) {
				console.log(JSON.parse(json_data.d))
				__fill_chamber_tree(JSON.parse(json_data.d))
			},
			error: function (response) {
				//alert(errorThrown.message);
				//alert('Error: ' + response.responseText)
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});
	}
}

function on_view_lot_data()
{
	row = $('#eq_lotlog_grid').datagrid('getSelected')
	if (!row) {
		$.messager.alert('AMS System', 'Select a Lot please. ')
		return
	}

	$('#window_lot_data').window({maximized: true}).window('open')
	
	var loopMax = $('#eq_lotlog_grid').datagrid('getSelected').lmax;
	if (ams_is_sim_mode()) {
		loopMax = 1
	}

	var data;
	data = [];
	for (var i = 1; i <= loopMax; i++)
	{
		data.push({ "text": i, "value": i });
	}
	$("#loop-num-wafer").combobox("loadData", data);
	$('#loop-num-wafer').combobox('select',data[0].text);
	$("#loop-num-chamber").combobox("loadData", data);
	$('#loop-num-chamber').combobox('select',data[0].text);
	
	init_wafer_tree()
	init_chamber_tree()
	on_mp_reset()
}

function on_refresh_view_log()
{
		if (ams_is_sim_mode()) {
		$.getJSON('lotlog_detail_log_01.json', function(json_data) {
			$('#tbl_lotlog_detail').datagrid({
					data: json_data.rows
				})
		})
	} else {
		// var __id = row.id
		// $.post(getWebServiceUrl("getLotDetailLog"),
		// 	{ 'id':__id },
		// 	function(json_data) {
		// 		$('#tbl_lotlog_detail').datagrid({
		// 			data: json_data.rows
		// 		})
		// 	}, 'json')
		// 	.fail(function(response) {
		// 		alert('Error: ' + response.responseText);
		// 	})

		var loopNum = $('#loop-num-detail').combobox('getValue');
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("getLotDetailLog"),
			data:JSON.stringify({
				"eqName":eqn,
				"lotId":row.id,
				"loopNum":loopNum
			}),
			dataType: 'json',
			success: function (json_data) {
				console.log(JSON.parse(json_data.d))
				$('#tbl_lotlog_detail').datagrid({
					data: JSON.parse(json_data.d).rows
				})
			},
			error: function (response) {
				//alert(errorThrown.message);
				//alert('Error: ' + response.responseText)
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});
	}
}

function on_view_log()
{
	row = $('#eq_lotlog_grid').datagrid('getSelected')
	if (!row) {
		$.messager.alert('AMS System', 'Select a Lot please. ')
		return
	}

	$('#window_detail_log').window('open')
	var loopMax = $('#eq_lotlog_grid').datagrid('getSelected').lmax;
	var data;
	data = [];
	for (var i = 1; i <= loopMax; i++)
	{
		data.push({ "text": i, "value": i });
	}
	$("#loop-num-detail").combobox("loadData", data);
	$('#loop-num-detail').combobox('select',data[0].text);
	
	on_refresh_view_log();
}

function on_view_stat_chart()
{
	row = $('#eq_lotlog_grid').datagrid('getSelected')
	if (!row) {
		//alert('Select a Lot please. ')
		$.messager.alert("Tips", "Select a Lot please.", "info");
		return
	}

	$('#window_stat_chart').window('open')
	
	var loopMax = $('#eq_lotlog_grid').datagrid('getSelected').lmax;
	var data;
	data = [];
	for (var i = 1; i <= loopMax; i++)
	{
		data.push({ "text": i, "value": i });
	}
	$("#loop-num-detail").combobox("loadData", data);
	$('#loop-num-detail').combobox('select',data[0].text);
}

function draw_stat_chart(json_data)
{
	/*
	设计：
	-- 根据lot数据信息，计算canvas及图形对象的尺寸，并调整canvas大小；
	   每个单元的条形框高度是固定值。
	   每个wafer一行，行高可估算一个固定值。约等于：(条高+文字高)*2*2 = 

	-- 绘制左侧的分隔栏

	-- 绘制顶部的时间刻度线
	   时间刻度的最大值，也就是最后完成的wafer的结束时间。

	*/
	var CHART_TOP = 100
	var CV_WIDTH = 4000
	var CV_HEIGHT = 3000
	var cv = document.getElementById('canvas_stat_chart')
	var ctx = cv.getContext("2d")
	var BAR_HEIGHT = 20
	var text_height = 16
	var wafer_bar_height = (BAR_HEIGHT + text_height) * 3
	var wafer_count = json_data.lot_data.length
	var SEC_PER_PX = 1 // seconds represented by 1 px
	var TIME_AXIS_ZERO_X = 100

//	console.log('wafer count: ' + wafer_count)
//	var max_time = 0
	for (var i = 0; i < wafer_count; i++) {
		var last_step = json_data.lot_data[i].steps[json_data.lot_data[i].steps.length - 1]
	//	max_time = Math.max(max_time, last_step.t2)
		json_data.lot_data[i]['_end_t'] = last_step.t2
	}

	// background
	ctx.fillStyle="#eeeeee"
	ctx.fillRect(0, CHART_TOP, CV_WIDTH, CV_HEIGHT)

	ctx.beginPath()
	ctx.lineWidth = 2
	ctx.strokeStyle = 'rgba(255,0,0,0.5)'
	ctx.moveTo(TIME_AXIS_ZERO_X, CHART_TOP)
	ctx.lineTo(TIME_AXIS_ZERO_X, CV_HEIGHT)

	// time line
	ctx.lineWidth = 1
	ctx.moveTo(TIME_AXIS_ZERO_X, CHART_TOP)
	ctx.lineTo(CV_WIDTH, CHART_TOP)
	var max_time = CV_WIDTH / SEC_PER_PX
	var __c = 0
	var MINUTE_LEN = 60 / SEC_PER_PX // 1 minute
	while ((__c*MINUTE_LEN) <= max_time) {
		ctx.moveTo(TIME_AXIS_ZERO_X + __c*MINUTE_LEN, CHART_TOP)
		ctx.lineTo(TIME_AXIS_ZERO_X + __c*MINUTE_LEN, CHART_TOP - 10)
		ctx.font = "11px Arial"
		ctx.fillStyle = "#222222"
		ctx.fillText(__c,
			TIME_AXIS_ZERO_X + __c*MINUTE_LEN + 1, CHART_TOP - 11, 50, text_height)
		__c++
	}
	ctx.stroke()


	ctx.beginPath()
	ctx.strokeStyle = '#999999'
	for (var i= 1; i < wafer_count+1; i++) {
		ctx.moveTo(TIME_AXIS_ZERO_X, CHART_TOP + wafer_bar_height*i)
		ctx.lineTo(CV_WIDTH, CHART_TOP + wafer_bar_height*i)
	}
	ctx.stroke()

	for (var i= 0; i < wafer_count; i++) {
		var wafer_text = json_data.lot_data[i].wid
		ctx.fillStyle="#000000"
		ctx.strokeStyle = "#0000ff"
		// wafer ID
		ctx.font = "15px Arial"
		ctx.fillStyle="#000000"
		ctx.fillText(wafer_text,
		 30, CHART_TOP + wafer_bar_height*(i+0.5) - text_height/2 + 2,
		 100, text_height)
		// wafer process time
		ctx.font = "11px Arial"
		ctx.fillStyle="#000000"
		ctx.fillText(json_data.lot_data[i]._end_t + ' (sec)',
		 15, CHART_TOP + wafer_bar_height*(i+0.5) + text_height,
		 135, text_height)

		var steps = json_data.lot_data[i].steps
		for (var k = 0; k < steps.length; k++) {
			var _left = TIME_AXIS_ZERO_X + parseFloat(steps[k].t1)
			var _top = CHART_TOP + wafer_bar_height*(i+0.4)
			var _width = steps[k].t2 - steps[k].t1
			var _height = BAR_HEIGHT

			// unit bar
			if (steps[k].pt1 != '') {
				ctx.fillStyle="#1c4587"
			} else {
				ctx.fillStyle="#6fa8dc"
			}
			ctx.fillRect(_left, _top, _width, _height)
			ctx.strokeRect(_left, _top, _width, _height)

			if (_width > 50) {
				// unit name
				ctx.font = "12px Arial"
				if (steps[k].pt1 == '') {
					ctx.fillStyle="#000000"
				} else {
					ctx.fillStyle = "#ffffff"
				}
				ctx.fillText(steps[k].un,
					_left + _width/2 - 10, _top + 14,
					135, text_height)
				// unit time
				ctx.font = "11px Arial"
				ctx.fillStyle="#000000"
				ctx.fillText(_width * SEC_PER_PX,
					_left + _width/2 - 10, _top - text_height + 10,
					135, text_height)
			}

			// processing bar
			if (steps[k].pt1 != '') {
				_left = TIME_AXIS_ZERO_X + parseFloat(steps[k].pt1)
				_top = CHART_TOP + wafer_bar_height*(i+0.4) + BAR_HEIGHT
				_width = steps[k].pt2 - steps[k].pt1
				_height = BAR_HEIGHT - 5
				ctx.fillStyle = "#ff9900"
				ctx.fillRect(_left, _top, _width, _height)
				ctx.strokeRect(_left, _top, _width, _height)
				// process time
				ctx.fillStyle = "#000000"
				ctx.font = "11px Arial"
				ctx.fillText(_width * SEC_PER_PX,
					_left + _width/2 - 10, _top + BAR_HEIGHT + 6,
					135, text_height)
			}
		}
	}
}

function on_query_by_loop()
{
	var title = $('.tabs-selected').text();
	if (title == "By Wafer")
	{
		init_wafer_tree()
	}
	else
	{
		init_chamber_tree()
	}
}

$(function () {
   $('#loop-num-wafer').combobox({
        onChange: function (newValue, oldValue) {
           init_wafer_tree()
        }
    });
});

$(function () {
   $('#loop-num-chamber').combobox({
        onChange: function (newValue, oldValue) {
           init_chamber_tree()
        }
    });
});

$(function () {
   $('#loop-num-detail').combobox({
        onChange: function (newValue, oldValue) {
           on_refresh_view_log()
        }
    });
});

$(function () {
   $('#loop-num-chart').combobox({
        onChange: function (newValue, oldValue) {
           on_refresh_chart()
        }
    });
});

$(function () {
   $('#loop-num-wrh').combobox({
        onChange: function (newValue, oldValue) {
           on_refresh_view_wafer_run_history()
        }
    });
});

$('#tbl_lotlog_wrh').datagrid({
    rowStyler:function(index, row){
    	var rowColor = 'color:' + row.Color + ';';
    	return rowColor;
        //if (row.isexception==1){
        //if (index == 1){
        //    return 'background-color:red;';
            //return 'color:red;';
        //}
    }
});

function on_wafer_run_history(){
	row = $('#eq_lotlog_grid').datagrid('getSelected')
	if (!row) {
		$.messager.alert('AMS System', 'Select a Lot please. ')
		return
	}

	$('#window_wafer_run_history').window('open')
	var loopMax = $('#eq_lotlog_grid').datagrid('getSelected').lmax;
	var data;
	data = [];
	for (var i = 1; i <= loopMax; i++)
	{
		data.push({ "text": i, "value": i });
	}
	$("#loop-num-wrh").combobox("loadData", data);
	$('#loop-num-wrh').combobox('select',data[0].text);
	
	on_refresh_view_wafer_run_history();
}

function on_refresh_view_wafer_run_history(){
	if (ams_is_sim_mode()) {
		$.getJSON('lotlog_wafer_run_history.json', function(json_data) {
			$('#tbl_lotlog_wrh').datagrid({
					data: json_data.rows
				})
		})
	} else {
		var loopNum = $('#loop-num-wrh').combobox('getValue');
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("getLotWaferRunHistory"),
			data:JSON.stringify({
				"eqName":eqn,
				"lotId":row.id,
				"loopNum":loopNum
			}),
			dataType: 'json',
			success: function (json_data) {
				console.log(JSON.parse(json_data.d))
				$('#tbl_lotlog_wrh').datagrid({
					data: JSON.parse(json_data.d).rows
				})
			},
			error: function (response) {
				$.messager.alert("Error", "Error: " + response.responseText, "error");
			}
		});
	}
}

////////////////////////////////////////////////////////
// for multi-plotting
var g_rtchart_mp = undefined
var mp_selected_wafer_pm_array = []
var mp_current_pm_type = ''

function on_mp_add()
{
//	alert('on_mp_add')
	var sel_item = $('#tree_wafer_mp').tree('getSelected')
	if (!sel_item) {
		$.messager.alert("Tips", "Select a PM please.", "info")
		return
	}
	var wafer_item = $('#tree_wafer_mp').tree('getParent', sel_item.target)
	if (!wafer_item) {
		$.messager.alert("Tips", "Select a PM please.", "info")
		return
	}
//	console.log(wafer_item.text + " / " + sel_item.text)
	pm_name = sel_item.text
	pm_type = get_pm_type(pm_name)
	if (pm_type == ''){
		$.messager.alert("Tips", "Abnormal pm type, please add again.", "info")
		return
	}
	if (mp_current_pm_type == '') {
		mp_current_pm_type = pm_type
		console.assert(mp_selected_wafer_pm_array.length == 0)
	}
	else {
		if (pm_type != mp_current_pm_type) {
			$.messager.alert("Tips", "PM type mismatch.", "info")
			return
		}
		for (var i = 0; i < mp_selected_wafer_pm_array.length; i++) {
			if (mp_selected_wafer_pm_array[i]['wfr'] == wafer_item.text &&
			mp_selected_wafer_pm_array[i]['pm'] == pm_name) {
				$.messager.alert("Tips", "Wafer/PM already added.", "info")
				return
			}
		}
	}
	var wfr_id = wafer_item.text
	var wp_inf = {}
	wp_inf['wfr'] = wfr_id
	wp_inf['pm'] = pm_name
	mp_selected_wafer_pm_array.push(wp_inf)

	// query new wafer-pm data
	lot_id = $('#eq_lotlog_grid').datagrid('getSelected').id
	// info
	var info = null;
	var node = $('#tree_wafer_mp').tree('getSelected');
	var unitName = node.text
	var waferNode = $('#tree_wafer_mp').tree('getParent', node.target)
	if (waferNode != undefined) {
		for (var i = 0; i < waferNode.children.length; i++) {
			if(unitName==waferNode.children[i].text){
				info = waferNode.children[i].info
				break
			}
		}
	}
	wfr_pm_data = get_wafer_pm_data(lot_id, wfr_id, pm_name, info)

	if (g_rtchart_mp == undefined) {
		g_rtchart_mp = new RTChart('chart_container_mp', true)
		g_rtchart_mp.reset()
	}

	if (g_rtchart_mp.mp_data_array.length == 0) {
		// parse variables
		var col = wfr_pm_data.columns[0]
		var va = []
		for (var k = 2; k < col.length; k++) {
			var vn = col[k].title
			g_rtchart_mp.pm_val_array.push(vn)
			va.push({ "text": vn, "id": (k - 2) })
		}
		//	console.log(va)
		$('#combo_var_mp').combobox('loadData', va)
		$('#combo_var_mp').combobox('setValue', 0)
	}

	g_rtchart_mp.add_wfr_pm_data(wfr_id, pm_name, wfr_pm_data)
//	on_mp_var_sel_changed(0)

//	g_rtchart_mp.redraw()
	$('#tbl_wfr_pm_mp').datagrid('appendRow', {wafer:wfr_id, pm:pm_name, visible:true})
	var ra = $('#tbl_wfr_pm_mp').datagrid('getRows')
	var idx = ra.length - 1
	$('#tbl_wfr_pm_mp').datagrid('checkRow', idx)
}

function on_mp_delete()
{
	alert('on_mp_delete')
}

function on_mp_reset()
{
	mp_current_pm_type = ''
	mp_selected_wafer_pm_array = []
	$('#combo_var_mp').combobox('clear').combobox('loadData', [])
	$('#tbl_wfr_pm_mp').datagrid('loadData',{rows:[]})
	if (g_rtchart_mp != undefined) {
		g_rtchart_mp.reset()
		g_rtchart_mp.redraw()
	}
}

function get_pm_type(pm_name)
{
	if (ams_is_sim_mode()) {
		return pm_name
	} else {
		$.ajaxSettings.async = false
		$.ajax({
			type: 'POST',
			contentType: 'application/json',
			url: getWebServiceUrl("getPMType"),
			data:JSON.stringify({
				"eqName":eqn,
				"pmName":pm_name
			}),
			dataType: 'json',
			success: function (json_data) {
				return json_data.d
			},
			error: function (response) {
				$.messager.alert("Error", "Error: " + response.responseText, "error")
				return ''
			}
		})
	}
}

function on_mp_var_sel_changed(new_index)
{
//	alert(g_rtchart_mp.pm_val_array[new_index])
	g_rtchart_mp.set_current_var(new_index)
	g_rtchart_mp.redraw(null)
}

function mp_dg_styler(value, row, index)
{
	var the_style = 'background-color:' + g_serie_color_array[index]
	return the_style
}

function do_show_wpm_serie(rowIndex, is_visible)
{
	g_rtchart_mp.show_wpm_serie(rowIndex, is_visible)
}

$(function () {
	$('#combo_var_mp').combobox({
		onChange: function (newValue, oldValue) {
		//	alert(newValue + '<=' + oldValue)
			on_mp_var_sel_changed(newValue)
		}
	});
})

$(function () {
	$('#tbl_wfr_pm_mp').datagrid({
		onCheck: function (rowIndex, rowData) {
			do_show_wpm_serie(rowIndex, true)
		}
	});
})

$(function () {
	$('#tbl_wfr_pm_mp').datagrid({
		onCheckAll: function (rows) {
			do_show_wpm_serie(-1, true)
		}
	});
})

$(function () {
	$('#tbl_wfr_pm_mp').datagrid({
		onUncheck: function (rowIndex, rowData) {
			do_show_wpm_serie(rowIndex, false)
		}
	});
})

$(function () {
	$('#tbl_wfr_pm_mp').datagrid({
		onUncheckAll: function (rows) {
			do_show_wpm_serie(-1, false)
		}
	});
})

</script>

</html>
